<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>精彩图集</title>
    <link rel="stylesheet" href="/css/computer/index.css">
    <link rel="stylesheet" href="/css/computer/atlas/atlascreate.css">
    <!-- 重置默认样式 -->
    <link rel="stylesheet" href="/css/resetcss.css">
    <style>
        
    </style>
</head>

<body>
    <div class="container-box">
        <div class="sidebar-box-left">
            <div class="sidebar">
                <div class="sidebar-header">
                    <a href="#" class="user" id="user-center">个人中心</a>
					<a href="#" class="user" id="user-login">登录/注册</a>
                </div>
                <nav class="sidebar-nav">
                    <ul>
                        <a class="homepage">
                            <li>主页</li>
                        </a><a href="" class="lifemoment">
                            <li>生活瞬间</li>
                        </a><a href="" class="tourlog">
                            <li>旅行记录</li>
                        </a><a href="" class="atlas">
                            <li class="active">精彩图集</li>
                        </a>
                    </ul>
                </nav>
            </div>
        </div>
        <div class="sidebar-box-right">
            <header>
                <div class="header-content">
                    <h1>记录生活中的美好时刻</h1>
                    <p class="subtitle">珍藏每一份感动，分享每一段旅程</p>
                    <a href="#" class="btn submit-edit">添加图片</a>
                    <a href="#" class="btn" id="submit-show">查看图集</a>
                </div>
            </header>

            <div class="container">
                <div class="container-edit">
                    <h1>图片上传</h1>
                    
                    <!-- 单图上传区 -->
                    <div class="section">
                        <div class="section-title">
                            <i>📷</i> 主图上传
                        </div>
                        <div class="upload-area" id="singleUploadArea">
                            <div class="upload-icon">⬆️</div>
                            <div class="upload-text">点击或拖拽上传主图</div>
                            <div class="upload-hint">仅支持JPG/PNG格式，大小不超过5MB</div>
                            <input type="file" id="singleUploadInput" accept="image/*" class="hidden">
                            <img id="mainPreview" class="main-preview" alt="主图预览">
                        </div>
                    </div>
                    
                    <!-- 标题和简介区 -->
                    <div class="section">
                        <div class="section-title">
                            <i>📝</i> 内容信息
                        </div>
                        <div class="form-group">
                            <label for="title">标题</label>
                            <input type="text" id="title" placeholder="请输入标题...">
                        </div>
                        <div class="form-group">
                            <label for="description">简介</label>
                            <textarea id="description" placeholder="请输入简介..."></textarea>
                        </div>
                    </div>
                    
                    <!-- 多图上传区 -->
                    <div class="section">
                        <div class="section-title">
                            <i>🖼️</i> 多图上传
                        </div>
                        <div class="upload-area" id="multiUploadArea">
                            <div class="upload-icon">⬆️</div>
                            <div class="upload-text">点击或拖拽上传多张图片</div>
                            <div class="upload-hint">最多可上传50张图片，每张不超过5MB</div>
                            <input type="file" id="multiUploadInput" accept="image/*" multiple class="hidden">
                        </div>
                        <div class="counter" id="counter">已上传 <span id="currentCount">0</span>/50 张</div>
                        <div class="thumbnail-container" id="thumbnailContainer"></div>
                    </div>
                </div>
            </div>

            <footer>
                <div class="footer-links">
                    <a href="#">关于我们</a>
                    <a href="#">联系方式</a>
                    <a href="#">隐私政策</a>
                    <a href="#">使用条款</a>
                </div>
                <p class="copyright">© 2023 美好时光记录 版权所有</p>
            </footer>
        </div>
    </div>
</body>


<script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>
<script src="/configfile/config.js"></script>
<script src="/script/token.js"></script>
<script type="module">
    //环境变量初始化
    //获取导航的a标签，并设置href
    const homepageElement = document.querySelector('.homepage'); // 返回第一个匹配的节点
    const lifemomentElement = document.querySelector('.lifemoment'); // 返回第一个匹配的节点
    const atlasElement = document.querySelector('.atlas'); // 返回第一个匹配的节点
    const userCenter = document.querySelector('#user-center');//获取个人中心DOM
	const userLogin = document.querySelector('#user-login');//获取登录注册DOM


	let server_ip = window.__ENV__.SERVER_IP;//服务器ip
	let home_ip = window.__ENV__.HOME_SERVER_IP;//首页ip
	homepageElement.href = home_ip;
	let life_ip = window.__ENV__.LIFEMOMENT_SERVER_IP;//生活瞬间
	lifemomentElement.href = life_ip;
	let atlas_ip = window.__ENV__.ATLAS_SERVER_IP;//图片集
	atlasElement.href = atlas_ip;
	let user_ip = window.__ENV__.USER_SERVER_IP;//用户
	userCenter.href = user_ip;
	userLogin.href = user_ip;

	//获取令牌
	let token = localStorage.getItem("token");

	//获取jwt令牌状态
	let jwtState = getJwtState(token);


	if(jwtState.success){
		userCenter.style.display = "block";
		userLogin.style.display = "none";
	}else{
		userCenter.style.display = "none";
		userLogin.style.display = "block";
	}

    //使用ejs模版来返回数据
    let resultData = <%- JSON.stringify(json) %>;

    //赋值数据
    (function (){
        let mainPreview = document.getElementById('mainPreview');
        let title = document.getElementById('title');
        let description = document.getElementById('description');

        
        mainPreview.src = server_ip + "/" + resultData.Atlascoverurl;
        title.value = resultData.Atlasname;
        description = resultData.Atlasdescription
    })();

    //添加图片方法
    function submitEdit(){
        let singleUploadInput = document.getElementById('singleUploadInput').files[0];
        //对名称进行监控，如果没有修改，那么使用数据库的名称
        let title = document.getElementById('title');
        let description = document.getElementById('description');
        let multiUploadInput = document.getElementById('multiUploadInput').files;
        
        //构建form表单，浏览器的方法
        let formData = new FormData();
        formData.append("singleImg",singleUploadInput);
        for(let i=0; i<thumbnails.length; i++){
            formData.append("arrayImg",thumbnails[i]);
        }
        formData.append("Atlasname",title.value);
        formData.append("Atlasmessage",description.value);
        

        axios
            .post(
                atlas_ip+"/updataatlas" + resultData.Atlas_id,
                formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        "Authorization": `Bearer ${token}`
                    },
                }
            )
            .then((res) => {
                //判断后端的报错信息。如果存在则保存失败
                // console.log(res.data);
                if(res.data.message.success){
                    alert("更新成功");
                }
            })
            .catch(err => {
                console.log(err);
            });
    }

    document.querySelector(".submit-edit").addEventListener("click",submitEdit);


    let thumbnails = [];

    //页面基础布局
    document.addEventListener('DOMContentLoaded', function() {
        // 单图上传
        const singleUploadArea = document.getElementById('singleUploadArea');
        const singleUploadInput = document.getElementById('singleUploadInput');
        const mainPreview = document.getElementById('mainPreview');
        
        // 多图上传
        const multiUploadArea = document.getElementById('multiUploadArea');
        const multiUploadInput = document.getElementById('multiUploadInput');
        const thumbnailContainer = document.getElementById('thumbnailContainer');
        const counter = document.getElementById('counter');
        const currentCount = document.getElementById('currentCount');
            
        let mainImage = null;
        const maxThumbnails = 50;
        
        // 单图上传区域点击事件
        singleUploadArea.addEventListener('click', () => {
            singleUploadInput.click();
        });
        
        // 单图文件选择事件
        singleUploadInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                const file = e.target.files[0];
                if (validateImage(file)) {
                    mainImage = file;
                    previewMainImage(file);
                    singleUploadArea.classList.add('active');
                }
            }
        });
        
        // 多图上传区域点击事件
        multiUploadArea.addEventListener('click', () => {
            multiUploadInput.click();
        });
        
        // 多图文件选择事件
        multiUploadInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                const files = Array.from(e.target.files);
                const validFiles = files.filter(file => validateImage(file));
                
                if (thumbnails.length + validFiles.length > maxThumbnails) {
                    alert(`最多只能上传${maxThumbnails}张图片`);
                    return;
                }
                
                validFiles.forEach(file => {
                    thumbnails.push(file);
                    previewThumbnail(file);
                });
                
                updateCounter();
            }
        });
        
        // 拖放功能
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            [singleUploadArea, multiUploadArea].forEach(area => {
                area.addEventListener(eventName, preventDefaults, false);
            });
        });
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        ['dragenter', 'dragover'].forEach(eventName => {
            singleUploadArea.addEventListener(eventName, highlightSingle, false);
            multiUploadArea.addEventListener(eventName, highlightMulti, false);
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            singleUploadArea.addEventListener(eventName, unhighlightSingle, false);
            multiUploadArea.addEventListener(eventName, unhighlightMulti, false);
        });
        
        function highlightSingle() {
            singleUploadArea.classList.add('active');
        }
        
        function unhighlightSingle() {
            singleUploadArea.classList.remove('active');
        }
        
        function highlightMulti() {
            multiUploadArea.classList.add('active');
        }
        
        function unhighlightMulti() {
            multiUploadArea.classList.remove('active');
        }
        
        // 单图拖放处理
        singleUploadArea.addEventListener('drop', handleSingleDrop, false);
        
        function handleSingleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            
            if (files.length > 0) {
                const file = files[0];
                if (validateImage(file)) {
                    mainImage = file;
                    previewMainImage(file);
                }
            }
        }
        
        // 多图拖放处理
        multiUploadArea.addEventListener('drop', handleMultiDrop, false);
        
        function handleMultiDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            
            if (files.length > 0) {
                const newFiles = Array.from(files).filter(file => validateImage(file));
                
                if (thumbnails.length + newFiles.length > maxThumbnails) {
                    alert(`最多只能上传${maxThumbnails}张图片`);
                    return;
                }
                
                newFiles.forEach(file => {
                    thumbnails.push(file);
                    previewThumbnail(file);
                });
                
                updateCounter();
            }
        }
        
        // 图片验证
        function validateImage(file) {
            const validTypes = ['image/jpeg', 'image/png'];
            if (!validTypes.includes(file.type)) {
                alert('只支持JPG和PNG格式的图片');
                return false;
            }
            
            if (file.size > 5 * 1024 * 1024) {
                alert('图片大小不能超过5MB');
                return false;
            }
            
            return true;
        }
        
        // 预览主图
        function previewMainImage(file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                mainPreview.src = e.target.result;
                mainPreview.style.display = 'block';
            };
            reader.readAsDataURL(file);
        }
        
        // 预览缩略图
        function previewThumbnail(file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                const thumbnailId = 'thumbnail-' + Date.now() + '-' + Math.floor(Math.random() * 1000);
                const thumbnailItem = document.createElement('div');
                thumbnailItem.className = 'thumbnail-item';
                thumbnailItem.id = thumbnailId;
                
                thumbnailItem.innerHTML = `
                    <img src="${e.target.result}" class="thumbnail-img" alt="缩略图">
                    <div class="remove-thumbnail" data-id="${thumbnailId}">×</div>
                `;
                
                thumbnailContainer.appendChild(thumbnailItem);
                
                // 添加删除事件
                const removeBtn = thumbnailItem.querySelector('.remove-thumbnail');
                removeBtn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    removeThumbnail(thumbnailId);
                });
            };
            reader.readAsDataURL(file);
        }
        
        // 删除缩略图
        function removeThumbnail(id) {
            const index = Array.from(thumbnailContainer.children).findIndex(el => el.id === id);
            if (index !== -1) {
                // 淡出动画
                const element = document.getElementById(id);
                element.style.opacity = '0';
                element.style.transform = 'scale(0.8)';
                
                setTimeout(() => {
                    thumbnailContainer.removeChild(element);
                    thumbnails.splice(index, 1);
                    updateCounter();
                }, 300);
            }
        }
        
        // 更新计数器
        function updateCounter() {
            currentCount.textContent = thumbnails.length;
            
            if (thumbnails.length >= maxThumbnails) {
                counter.classList.add('warning');
            } else {
                counter.classList.remove('warning');
            }
        }
        
    });

    //跳转查看图集方法
    (function (){
        let submitShow = document.getElementById("submit-show");
        //更新
        submitShow.addEventListener("click", ()=>{
            axios
                .post(
                    atlas_ip + "/gettempcode",
                    {},
                    {
                        headers: {
                            "Authorization": `Bearer ${token}`
                        }
                    }
                )
                .then((res) => {
                    //判断后端的报错信息。如果存在则保存失败
                    console.log(res.data);
                    let tempToken = res.data.tempToken;
                    //跳转新页面
                    let href = `${atlas_ip}/show${resultData.Atlas_id}`;
                    window.location.href = `${href}?tempToken=${tempToken}`;
                })
                .catch(err => {
                    console.log(err);
                    alert("拒绝访问");
                });
        });
    })();



</script>

</html>